package com.sql.readwrite.aspect;

import com.sql.readwrite.commons.mythread.DBContextHolder;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * @date 2020/11/16 9:23
 */
@Aspect
@Component
public class DataSourceAop {

    /**
     * 没有Master注解，且是service中的select* 或 get* 方法 拦截。
     * 从库切换
     */
    @Pointcut(
            "!@annotation(com.sql.readwrite.annotation.Master)"+
            "&& (" +
            "execution(* com.sql.readwrite.service..*.select*(..))"+
            "|| " +
            "execution(* com.sql.readwrite.service..*.get*(..))" +
            ")")
    public void readPointcut(){

    }

    /**
     * 主库切换
     */
    @Pointcut("@annotation(com.sql.readwrite.annotation.Master) " +
            "|| execution(* com.sql.readwrite.service..*.insert*(..)) " +
            "|| execution(* com.sql.readwrite.service..*.add*(..)) " +
            "|| execution(* com.sql.readwrite.service..*.update*(..)) " +
            "|| execution(* com.sql.readwrite.service..*.edit*(..)) " +
            "|| execution(* com.sql.readwrite.service..*.delete*(..)) " +
            "|| execution(* com.sql.readwrite.service..*.remove*(..))")
    public void writePointcut() {

    }

    @Before("readPointcut()")
    public void read(){
        DBContextHolder.slave();
    }

    @Before("writePointcut()")
    public void write(){
        DBContextHolder.master();
    }

}
